package xlogin

import (
	"encoding/json"
	"time"

	"gitee.com/xiaoyutab/xgotool/https"
	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/optional/xnsq"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 刷新Token信息
//
//	NSQ	xlogin.ref-token	<CodeToken>
func NsqRefToken(param []byte) error {
	pm := CodeToken{}
	if err := json.Unmarshal(param, &pm); err != nil {
		return err
	}
	tokens := CodeToken{}
	var err error
	// 进行刷新token
	switch pm.XloginType {
	case TypesWps:
		err = https.Get("https://openapi.wps.cn/oauthapi/v2/token/refresh", map[string]string{
			"appid":         _default.Conf[TypesWps].AppId,
			"appkey":        _default.Conf[TypesWps].AppSecret,
			"refresh_token": pm.RefreshToken,
		}, map[string]string{
			"Content-Type": "application/json",
		}).Json(&tokens, "token")
	case TypesWechat:
		err = https.Get("https://api.weixin.qq.com/sns/oauth2/refresh_token", map[string]string{
			"appid":         _default.Conf[TypesWps].AppId,
			"grant_type":    "refresh_token",
			"refresh_token": pm.RefreshToken,
		}, map[string]string{}).Json(&tokens)
	default:
		err = xerror.New("该类型暂不支持刷新")
	}
	if err != nil {
		return err
	}
	if tokens.ExpiresIn == 0 {
		return xerror.New("三方token获取失败")
	}
	tokens.XloginType = pm.XloginType
	xcache.SetStruct(xcache.Key("xlogin.openid2token", tokens.Openid, pm.XloginType), tokens)
	// 提前十分钟进行刷新token
	xnsq.SetDef("xlogin.ref-token", tokens, time.Second*time.Duration(tokens.ExpiresIn-600))
	return nil
}
